package com.glela.serial.service.impl;

import com.glela.common.constant.CommonConstants;
import com.glela.common.exception.BizException;
import com.glela.constant.BizConstant;
import com.glela.goods.mapper.GoodsDetailMapper;
import com.glela.goods.mapper.GoodsMapper;
import com.glela.goods.mapper.GoodsNavigateMapper;
import com.glela.goods.model.Goods;
import com.glela.goods.model.GoodsDetail;
import com.glela.goods.model.GoodsImgType;
import com.glela.goods.model.GoodsNavigate;
import com.glela.goods.model.vo.goods.GoodsSimpleVo;
import com.glela.goods.model.vo.goods.SimpleGoods;
import com.glela.goods.service.GoodsService;
import com.glela.platform.mapper.UserFansMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.User;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserService;
import com.glela.platform.util.DateUtils;
import com.glela.serial.mapper.*;
import com.glela.serial.model.*;
import com.glela.serial.model.dto.TalentSerialDTO;
import com.glela.serial.model.request.RequestSerial;
import com.glela.serial.model.response.*;
import com.glela.serial.model.response.hometitle.ResponseHomeTitle;
import com.glela.serial.model.response.hometitle.ResponseHomeTitleInfo;
import com.glela.serial.service.SerialService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 期资讯
 *
 * @author 卫耀华
 *
 */
@Service("serialService")
public class SerialServiceImpl implements SerialService {
	@Autowired
	private SerialMapper					serialMapper;
	@Autowired
	private SerialBrandMapper				serialBrandMapper;
	@Autowired
	private TalentSerialEditAndShareMapper	talentSerialEditAndShareMapper;
	@Autowired
	private TalentSerialMapper				talentSerialMapper;
	@Autowired
	private GoodsService					goodsService;
	@Autowired
	private UserMapper						userMapper;
	@Autowired
	private TalentSerialGoodsMapper			talentSerialGoodsMapper;
	@Autowired
	private SerialGoodsMapper				serialGoodsMapper;
	@Autowired
	private GoodsMapper						goodsMapper;
	@Autowired
	private SerialContentMapper				serialContentMapper;
	@Autowired
	private TalentSerialContentMapper		talentSerialContentMapper;
	@Autowired
	private GoodsNavigateMapper				goodsNavigateMapper;
	@Autowired
	private GoodsDetailMapper				goodsDetailMapper;
	@Autowired
	private UserService						userService;
	@Autowired
	private UserFansMapper					userFansMapper;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	@Autowired
	private indexPageContentMapper indexPageContentMapper;

	@Override
	public List<ResponseHomeTitle> findSerials() {
		List<Serial> selectSerials = this.serialMapper.selectSerials();
		List<ResponseHomeTitle> _response_home_tile_list = new ArrayList<ResponseHomeTitle>();
		if (CollectionUtils.isEmpty(selectSerials)) {
			ResponseHomeTitle _new_response_home_time = new ResponseHomeTitle();
			_response_home_tile_list.add(_new_response_home_time);
			_new_response_home_time.setSerialId(-1);
			_new_response_home_time.setTitle("因为有你");
			_new_response_home_time.setSkipType(1);
			ResponseHomeTitle _new_response_home_time_2 = new ResponseHomeTitle();
			_response_home_tile_list.add(_new_response_home_time_2);
			_new_response_home_time_2.setSerialId(-1);
			_new_response_home_time_2.setTitle("所以快乐");
			_new_response_home_time_2.setSkipType(3);
		} else {
			for (Serial serial : selectSerials) {
				ResponseHomeTitle _new_response_home_time = new ResponseHomeTitle();
				_response_home_tile_list.add(_new_response_home_time);
				_new_response_home_time.setSerialId(serial.getId());
				_new_response_home_time.setTitle(serial.getTitle());
				_new_response_home_time.setSkipType(serial.getSkipType());
			}
		}
		return _response_home_tile_list;
	}

	@Override
	public ResponseHomeTitleInfo findSerialInfo(RequestSerial requestSerial) {
		BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("h5_activity_url");
		int type = baseRestrictions.getExperience();
		ResponseHomeTitleInfo returnSerial = new ResponseHomeTitleInfo();
		Serial checkSerial = this.serialMapper.selectSerialById(requestSerial.getSerialId());
		if (checkSerial == null) {
			return returnSerial;
		}
		//		User _loginUser = userService.getUser(requestSerial.getUserId());
		//		User _check_recommend_user = userService.selectRecommendFromByUserId(requestSerial.getUserId());
		returnSerial.setSerialId(checkSerial.getId());
		String nowTime = DateUtils.getNowString(DateUtils.DATE_TIME_FORMAT);
		//封装其它数据
		switch (checkSerial.getSkipType()) {
			case 3://专题页，封装商品信息
				//				PageHelper.startPage(requestSerial.getPageNum(), requestSerial.getPageSize());
				//				Page<Goods> goodss = (Page<Goods>) serialGoodsMapper.selectGoodsBySerialId(requestSerial.getSerialId());
				//				for (Goods goods : goodss) {
				//					ResponseHomeTitleInfoGoodsVo vo = new ResponseHomeTitleInfoGoodsVo();
				//					returnSerial.getGoodsList().add(vo);
				//					vo.setGoodsId(goods.getId());
				//					vo.setName(goods.getName());
				//					vo.setLabelName(goods.getLabelName());
				//					vo.setSelfSupport(goods.getSelfSupport());
				//					vo.setOfflineTime(goods.getOfflineTime());
				//					vo.setOnlineTime(goods.getOnlineTime());
				//					vo.setInventoryAvlNum(goods.getInventoryNum());
				//					//查询动态价格
				//					GoodsPrice goodsViewPriceForProduct = goodsService.getGoodsViewPriceForGoods(_loginUser, goods.getId());
				//					if (goodsViewPriceForProduct != null) {
				//						vo.setLowestPrice(goodsViewPriceForProduct.getSalePrice());
				//						vo.setSuggestedPrice(goodsViewPriceForProduct.getMarketPirce());
				//					} else {
				//						vo.setLowestPrice(goods.getLowestPrice());
				//						vo.setSuggestedPrice(goods.getSuggestedPrice());
				//					}
				//					//查询实时库存
				//					vo.setInventoryAvlNum(inventoryService.findDynaByGoodsId(goods.getId()));
				//				}
				//				returnSerial.setHasGoodsNextPage(goodss.toPageInfo().isHasNextPage());
			case 1://首页不跳转，封装图片
				if (requestSerial.getPageNum() <= 1) {
					/*List<SerialContent> contents = serialContentMapper.selectSerialContentListBySerialId(requestSerial.getSerialId());
					for (SerialContent sc : contents) {
						if (type == sc.getJumpStyle()) {//去除新增的类型，兼容老版本
							continue;
						}
						ResponseSerialContent rsc = new ResponseSerialContent();
						rsc.setSerialContentId(sc.getId());
						rsc.setSerialId(sc.getSerialId());
						rsc.setImagePath(sc.getImagePath());
						rsc.setJumpStyle(sc.getJumpStyle());
						rsc.setJumpTo(sc.getJumpTo());
						rsc.setImgWidth(sc.getImgWidth());
						rsc.setImgHeight(sc.getImgHeight());
						returnSerial.getSerialContentImages().add(rsc);
					}*/
					//将首页提轮播图作为新表存储（index_page_content）-------2018-01-19
					List<indexPageContent> contents = indexPageContentMapper.selectIndexPageContentListBySerialId(requestSerial.getSerialId(),nowTime);
					if (!CollectionUtils.isEmpty(contents)) {
						for (indexPageContent sc : contents) {
							if (type == sc.getJumpStyle()) {//去除新增的类型，兼容老版本
								continue;
							}
							ResponseSerialContent rsc = new ResponseSerialContent();
							rsc.setSerialContentId(sc.getId());
							rsc.setSerialId(sc.getSerialId());
							rsc.setImagePath(sc.getImagePath());
							rsc.setJumpStyle(sc.getJumpStyle());
							rsc.setJumpTo(sc.getJumpTo());
							rsc.setImgWidth(sc.getImgWidth() == null?0:sc.getImgWidth());
							rsc.setImgHeight(sc.getImgHeight()==null?0:sc.getImgHeight());
							returnSerial.getSerialContentImages().add(rsc);
						}
					}
				}
				break;

			default:

				break;
		}
		return returnSerial;
	}
	/**
	 * @Description: 期内容-轮播图列表（根据期内容类型判断是否跳转活动详情页）
	 * @Author: zhangrenjie
	 * @Date: 2018/1/11 17:43
	 *
	 */
	/*@Override
	public ResponseHomeTitleInfo findSerialInfoNew(RequestSerial requestSerial, HttpServletRequest request) {
		ResponseHomeTitleInfo returnSerial = new ResponseHomeTitleInfo();
		Serial checkSerial = this.serialMapper.selectSerialById(requestSerial.getSerialId());
		if (checkSerial == null) {
			return returnSerial;
		}
		BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("h5_activity_url");
		if (null == baseRestrictions) {
			throw new RuntimeException("H5活动详情页访问域名为空，请检查数据库基础配置信息表");
		}
		String url = baseRestrictions.getName();
		int type = baseRestrictions.getExperience();
		String phoneType = CommonConstants.PHONE_CLIENT_ANDROID;
		if (!StringUtils.isBlank(request.getHeader("phoneType"))) {
			phoneType = request.getHeader("phoneType").toLowerCase();
		}
		returnSerial.setSerialId(checkSerial.getId());
		String nowTime = DateUtils.getNowString(DateUtils.DATE_TIME_FORMAT);
		switch (checkSerial.getSkipType()) {
			case 3://专题页，可以不处理，也可以和类型1做同样处理
			case 1://首页不跳转，封装图片
				if (requestSerial.getPageNum() <= 1) {
					*//*List<SerialContent> contents = serialContentMapper.selectSerialContentListBySerialId(requestSerial.getSerialId());
					for (SerialContent sc : contents) {
						ResponseSerialContent rsc = new ResponseSerialContent();
						rsc.setSerialContentId(sc.getId());
						rsc.setSerialId(sc.getSerialId());
						rsc.setImagePath(sc.getImagePath());
						rsc.setJumpStyle(sc.getJumpStyle());
						rsc.setJumpTo(sc.getJumpTo());
						if (sc.getJumpStyle()==type) {//跳转H5活动详情，此时JumpTo就是活动父ID
							rsc.setSkipUrl(url+"id="+sc.getJumpTo()+"&"+phoneType+"=1"+"&t="+System.currentTimeMillis());
						}
						rsc.setImgWidth(sc.getImgWidth());
						rsc.setImgHeight(sc.getImgHeight());
						returnSerial.getSerialContentImages().add(rsc);
					}*//*
					//将首页提轮播图作为新表存储（index_page_content）-------2018-01-19
					List<indexPageContent> contents = indexPageContentMapper.selectIndexPageContentListBySerialId(requestSerial.getSerialId(),nowTime);
					if (!CollectionUtils.isEmpty(contents)) {
						for (indexPageContent sc : contents) {
							ResponseSerialContent rsc = new ResponseSerialContent();
							rsc.setSerialContentId(sc.getId());
							rsc.setSerialId(sc.getSerialId());
							rsc.setImagePath(sc.getImagePath());
							rsc.setJumpStyle(sc.getJumpStyle());
							rsc.setJumpTo(sc.getJumpTo());
							if (sc.getJumpStyle()==type) {//跳转H5活动详情，此时JumpTo就是活动父ID
								rsc.setSkipUrl(url+"id="+sc.getJumpTo()+"&"+phoneType+"=1"+"&t="+System.currentTimeMillis());
							}
							rsc.setImgWidth(sc.getImgWidth() == null?0:sc.getImgWidth());
							rsc.setImgHeight(sc.getImgHeight()==null?0:sc.getImgHeight());
							returnSerial.getSerialContentImages().add(rsc);
						}
					}
				}
				break;
			default:

				break;
		}
		return returnSerial;
	}*/
	/**
	 * @Description: 期内容-轮播图列表-无需参数（根据期内容类型判断是否跳转活动详情页）
	 * @Author: zhangrenjie
	 * @Date: 2018/1/24 12:10
	 *
	 */
	@Override
	public ResponseHomeTitleInfo findSerialInfoNew(RequestSerial requestSerial, HttpServletRequest request) {
		ResponseHomeTitleInfo returnSerial = new ResponseHomeTitleInfo();
//		Serial checkSerial = this.serialMapper.selectSerialById(requestSerial.getSerialId());
//		if (checkSerial == null) {
//			return returnSerial;
//		}
		BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("h5_activity_url");
		if (null == baseRestrictions) {
			throw new RuntimeException("H5活动详情页访问域名为空，请检查数据库基础配置信息表");
		}
		String url = baseRestrictions.getName();
		int type = baseRestrictions.getExperience();
		String phoneType = CommonConstants.PHONE_CLIENT_ANDROID;
		if (!StringUtils.isBlank(request.getHeader("phoneType"))) {
			phoneType = request.getHeader("phoneType").toLowerCase();
		}
//		returnSerial.setSerialId(checkSerial.getId());
		String nowTime = DateUtils.getNowString(DateUtils.DATE_TIME_FORMAT);
		//将首页提轮播图作为新表存储（index_page_content）-------2018-01-19
//		List<indexPageContent> contents = indexPageContentMapper.selectIndexPageContentListBySerialId(requestSerial.getSerialId(),nowTime);
		List<indexPageContent> contents = indexPageContentMapper.selectIndexPageContentList(nowTime);
		if (!CollectionUtils.isEmpty(contents)) {
			for (indexPageContent sc : contents) {
				ResponseSerialContent rsc = new ResponseSerialContent();
				rsc.setSerialContentId(sc.getId());
				rsc.setSerialId(sc.getSerialId());
				rsc.setImagePath(sc.getImagePath());
				rsc.setJumpStyle(sc.getJumpStyle());
				rsc.setJumpTo(sc.getJumpTo());
				if (sc.getJumpStyle()==type) {//跳转H5活动详情，此时JumpTo就是活动父ID
					rsc.setActivityId(sc.getJumpTo());//活动Id用于分享
					rsc.setSkipUrl(url+"id="+sc.getJumpTo()+"&"+phoneType+"=1"+"&t="+System.currentTimeMillis());
					if(requestSerial.getUserId() != null && requestSerial.getUserId() > 0) {
						if(StringUtils.equals(phoneType, CommonConstants.PHONE_CLIENT_ANDROID) || StringUtils.equals(phoneType, CommonConstants.PHONE_CLIENT_IOS)) {
							String _url = rsc.getSkipUrl();
							if(StringUtils.isNotBlank(_url)) {
								rsc.setSkipUrl(_url + "&talentId=" + requestSerial.getUserId());
							}
						}
					}
				}
				rsc.setImgWidth(sc.getImgWidth() == null?0:sc.getImgWidth());
				rsc.setImgHeight(sc.getImgHeight()==null?0:sc.getImgHeight());
				returnSerial.getSerialContentImages().add(rsc);
			}
		}
		return returnSerial;
	}

	/**
	 * 普通期不需要商品，只要商品的个数
	 * @param serial
	 * @return
	 */
	public SimpleSerialVo nomalSerialNoGoods(Serial serial) {
		SimpleSerialVo simpleSerialVo = new SimpleSerialVo();
		BeanUtils.copyProperties(serial, simpleSerialVo);
		List<Goods> goodss = serialGoodsMapper.selectGoodsBySerialId(serial.getId());
		simpleSerialVo.setGoodsNum(goodss == null ? 0 : goodss.size());
		simpleSerialVo.setSerialId(serial.getId());
		return simpleSerialVo;
	}

	/**
	 * 普通期需要商品，商品的价格按照角色等级处理
	 *
	 * @param serial
	 * @return
	 */
	private ResponseSerial toNomalSerialNeedGoodsVo(Serial serial, int roleId) {
		ResponseSerial rs = new ResponseSerial();
		BeanUtils.copyProperties(serial, rs);
		List<GoodsSimpleVo> goodsList = new ArrayList<GoodsSimpleVo>();// IOS说遇到NULL就会闪退，这里预处理new一个空数组[]
		// 数据库里一次查出所有要展示的C区正常商品列表信息，查出来的价格是库存价，如果是会员或更高角色，下面单独处理
		goodsList = serialGoodsMapper.selectGoodsVoBySerialId(serial.getId());
		if (goodsList != null && goodsList.size() > 0) {
			for (GoodsSimpleVo vo : goodsList) {
				vo.setGoodNavigateImage(vo.getNavigateImage());
				// 如果当前登录的用户是会员或更高角色，这里看到会员价
				vo.setLowestPrice(goodsService.getLowestPrice(vo, 0, roleId));
			}
		}
		rs.setGoodsList(goodsList);
		rs.setGoodsNum(goodsList.size());
		rs.setSerialId(serial.getId());
		return rs;
	}

	/**
	 * 达人期-----数量----商品列表
	 *
	 * @author 卫耀华
	 * @param talentSerials
	 * @param userId
	 * @return
	 */
	private List<ResponseSerial> talentSerialNeedGoods(List<TalentSerial> talentSerials, int roleId) {
		List<ResponseSerial> voList = new ArrayList<ResponseSerial>();
		if (talentSerials != null && talentSerials.size() > 0) {
			for (TalentSerial ts : talentSerials) {
				ResponseSerial vo = new ResponseSerial();
				BeanUtils.copyProperties(ts, vo);
				vo.setSerialId(ts.getId());// 达人期ID
				vo.setCoverImgpath(ts.getImagePath());
				//达人期下的C区商品
				List<Goods> goodss = talentSerialGoodsMapper.selectGoodsByTalentSerialId(ts.getId());
				List<GoodsSimpleVo> goodsList = new ArrayList<GoodsSimpleVo>();
				int goodsNum = 0;
				if (goodss != null && goodss.size() > 0) {
					for (Goods goods : goodss) {
						if (goods != null) {
							GoodsSimpleVo gvo = goodsService.toSimpleGoodsVo(goods, 0, roleId);
							if (gvo != null) {
								goodsList.add(gvo);
								goodsNum = goodsNum + 1;
							}
						}
					}
				}
				vo.setGoodsList(goodsList);
				vo.setGoodsNum(goodsNum);// 商品数量
				vo.setTalentId(ts.getTalentId());
				voList.add(vo);
			}
		}
		return voList;
	}

	/**
	 * 首页今日推荐5个
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public List<ResponseSerial> getSerialsToday(long userId) {
		int roleId = 0;
		if (userId > 0) {
			User user = userMapper.selectByPrimaryKey(userId);
			if (user != null) {
				roleId = user.getRoleId();
			}
		}
		// 最新的五条期资讯 
		List<Serial> list = serialMapper.selectSerialLimit5();
		List<ResponseSerial> voList = new ArrayList<ResponseSerial>();
		if (list != null && list.size() > 0) {
			for (Serial serial : list) {
				// 添加商品并处理商品价格
				voList.add(toNomalSerialNeedGoodsVo(serial, roleId));
			}
		}
		return voList;
	}

	/**
	 * 品牌下发布的期，分页
	 */
	@Override
	public List<SimpleSerialVo> selectSerialsByBrandId(int brandId, int pageLimit, int pageSize) {
		List<SimpleSerialVo> rsList = new ArrayList<SimpleSerialVo>();
		// 品牌下的期资讯ID
		List<Integer> serialIdList = serialBrandMapper.selectSerialIdListByBrandId(brandId);
		if (serialIdList != null && serialIdList.size() > 0) {
			List<Serial> list = serialMapper.selectSerialListByPaginiton(serialIdList, pageLimit, pageSize);
			if (list != null && list.size() > 0) {
				for (Serial s : list) {
					rsList.add(nomalSerialNoGoods(s));
				}
			}
		}
		return rsList;
	}

	/**
	 * 品牌下发布的期
	 */
	@Override
	public int countSerialsByBrandId(int brandId) {
		int num = 0;
		List<Integer> serialIdList = serialBrandMapper.selectSerialIdListByBrandId(brandId);
		if (serialIdList != null && serialIdList.size() > 0) {
			num = serialMapper.selectSerialNumForBrand(serialIdList);
		}
		return num;
	}

	/**
	 * 福利社的期
	 */
	@Override
	public List<SimpleSerialVo> selectFulisheSerialList(int startIndex, int pageSize) {
		List<SimpleSerialVo> voList = new ArrayList<SimpleSerialVo>();
		List<Serial> list = serialMapper.selectFulisheSerialList(startIndex, pageSize);
		if (list != null && list.size() > 0) {
			for (Serial s : list) {
				voList.add(nomalSerialNoGoods(s));
			}
		}
		return voList;
	}

	/**
	 * 福利社的期
	 */
	@Override
	public int selectFulisheSerialNum() {
		return serialMapper.selectFulisheSerialNum();
	}

	/**
	 * 达人社区（最新、讲师、达人、关注）
	 *
	 * @param tabIndex
	 * @param userId
	 * @param startIndex
	 * @param pageSize
	 * @return
	 */
	@Override
	public List<ResponseTalentSerial> community(int tabIndex, Long userId, int startIndex, Integer pageSize) throws BizException {
		List<ResponseTalentSerial> respList = new ArrayList<ResponseTalentSerial>();
		List<TalentSerialDTO> serials = new ArrayList<TalentSerialDTO>();
		if (BizConstant.SHEQU_NEW == tabIndex) {// 最新(讲师和达人发布的期资讯)
			serials = talentSerialEditAndShareMapper.selectAllTalentSerialNew(startIndex, pageSize);
		} else if (BizConstant.SHEQU_JIANGSHI == tabIndex) {// 讲师发布的期资讯
			serials = talentSerialEditAndShareMapper.selectTalentSerialByRoleId7(startIndex, pageSize);
		} else if (BizConstant.SHEQU_DAREN == tabIndex) {// 达人发布的期资讯
			serials = talentSerialEditAndShareMapper.selectTalentSerialByRoleId3456(startIndex, pageSize);
		} else if (BizConstant.SHEQU_GUANZHU == tabIndex) {// 我关注的讲师和达人发布的期资讯
			serials = talentSerialEditAndShareMapper.selectAllTalentSerialUserLiked(userId, startIndex, pageSize);
		}
		if (serials != null && serials.size() > 0) {
			int roleId = 0;
			User user = userMapper.selectByPrimaryKey(userId);
			if (user != null) {
				roleId = user.getRoleId();
			}
			List<Long> talentIdLiked = userFansMapper.selectTalentIdListByUserId(userId);
			for (TalentSerialDTO dto : serials) {
				ResponseTalentSerial resp = new ResponseTalentSerial();
				if (talentIdLiked.contains(dto.getTalentId())) {
					resp.setIsEnjoy(BizConstant.ENJOY_TYPE_Y);// 是否关注此达人
				}
				resp.setSerialId(dto.getId());// 达人期id
				resp.setTitle(dto.getTitle());// 标题
				resp.setCoverImgpath(dto.getImagePath());// 封面图
				resp.setSeeCount(dto.getSeeCount());// 浏览数
				List<GoodsSimpleVo> list = getGoodsBySerialId(dto.getId(), 0, roleId);
				resp.setGoodsList(list);// 商品列表
				resp.setGoodsNum(list.size());// 商品数量
				resp.setTalentId(dto.getTalentId());// 达人id
				resp.setPersonDescription(dto.getSynopsis());// 达人简介
				resp.setTalentHeadPhoto(dto.getPicture());// 达人头像
				resp.setTalentNickName(dto.getNickName());// 达人昵称
				resp.setRoleId(dto.getRoleId());
				respList.add(resp);
			}
		}
		return respList;
	}

	/**
	 * 达人社区（最新、讲师、达人、关注）分页总条数
	 *
	 * @param tabIndex
	 * @param userId
	 * @return
	 */
	@Override
	public int countCommunity(int tabIndex, Long userId) throws BizException {
		int count = 0;
		if (BizConstant.SHEQU_NEW == tabIndex) {// 最新(讲师和达人发布的期资讯)
			count = talentSerialEditAndShareMapper.countTalentSerialNew();
		} else if (BizConstant.SHEQU_JIANGSHI == tabIndex) {// 讲师发布的期资讯
			count = talentSerialEditAndShareMapper.countTalentSerialByRoleId7();
		} else if (BizConstant.SHEQU_DAREN == tabIndex) {// 达人发布的期资讯
			count = talentSerialEditAndShareMapper.countTalentSerialByRoleId3456();
		} else if (BizConstant.SHEQU_GUANZHU == tabIndex) {// 我关注的讲师和达人发布的期资讯
			count = talentSerialEditAndShareMapper.countTalentSerialUserLiked(userId);
		}
		return count;
	}

	/**
	 * 达人期下面的商品列表
	 *
	 * @param serialId
	 * @param roleId
	 * @return
	 */
	public List<GoodsSimpleVo> getGoodsBySerialId(int serialId, int shareUserRoleId, int roleId) {
		List<SimpleGoods> goodsList = talentSerialGoodsMapper.selectGoodsBySerialId(serialId);
		return goodsService.simpleGoodsTrans(goodsList, shareUserRoleId, roleId);
	}

	/**
	 * 首页今日推荐旁边点击更多
	 *
	 * @author 卫耀华
	 * @date 2016-10-21
	 * @return
	 */
	@Override
	public List<ResponseSerial> getMoreNomalSerialList(long userId, int startPage, int pageSize) {
		List<ResponseSerial> voList = new ArrayList<ResponseSerial>();
		// 取首页期的前5个ID
		List<Integer> idList = serialMapper.selectSerialIdsLimit5();
		int roleId = 0;
		User user = userMapper.selectByPrimaryKey(userId);
		if (user != null) {
			roleId = user.getRoleId();
		}
		if (idList != null && idList.size() > 0) {
			// 分页查询期资讯 不包含ID在idList内的期资讯
			List<Serial> list = serialMapper.getMoreNomalSerialList(idList, startPage, pageSize);
			if (list != null && list.size() > 0) {
				for (Serial serial : list) {
					voList.add(toNomalSerialNeedGoodsVo(serial, roleId));
				}
			}
		}
		return voList;
	}

	/**
	 * 首页今日推荐旁边点击更多,统计总条数
	 *
	 * @author 卫耀华
	 * @date 2016-10-21
	 * @return
	 */
	@Override
	public int countMoreNomalSerialNum() {
		List<Integer> idList = serialMapper.selectSerialIdsLimit5();
		int num = 0;
		if (idList != null && idList.size() > 0) {
			num = serialMapper.countMoreNomalSerialNum(idList);
		}
		return num;
	}

	/**
	 * 普通期详情
	 *
	 * @author 卫耀华
	 * @param serialId
	 * @return
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public ResponseSerialDetail getNomalSerialDetailBySerialId(long userId, long shareUserId, int serialId) {
		int roleId = 0;
		User user = userMapper.selectByPrimaryKey(userId);
		if (user != null) {
			roleId = user.getRoleId();
		}
		int shareRoleId = 0;
		User shareUser = userMapper.selectByPrimaryKey(shareUserId);
		if (shareUser != null) {
			shareRoleId = shareUser.getRoleId();
		}
		Serial serial = serialMapper.selectSerialById(serialId);
		ResponseSerialDetail detail = null;
		if (serial != null) {
			detail = new ResponseSerialDetail();
			BeanUtils.copyProperties(serial, detail);
			detail.setSerialId(serial.getId());
			detail.setCoverImgpath(serial.getWxBigImgpath());// 官方期的详情上面的大图，是微信大图，和外面的不一样
			List<Goods> goodss = serialGoodsMapper.selectGoodsBySerialId(serialId);
			List<GoodsSimpleVo> simpleVoList = new ArrayList<GoodsSimpleVo>();
			if (goodss != null && goodss.size() > 0) {
				for (Goods goods : goodss) {
					if (goods != null) {
						GoodsSimpleVo vo = goodsService.toSimpleGoodsVo(goods, shareRoleId, roleId);
						if (vo != null) {
							simpleVoList.add(vo);
						}
					}
				}
			}
			// 商品列表
			detail.setGoodsList(simpleVoList);
			// 期下面的图片列表
			List<ResponseSerialContent> contentList = new ArrayList<ResponseSerialContent>();
			//期资讯内容
			List<SerialContent> contents = serialContentMapper.selectSerialContentListBySerialId(serialId);
			if (contents != null && contents.size() > 0) {
				for (SerialContent sc : contents) {
					ResponseSerialContent rsc = new ResponseSerialContent();
					BeanUtils.copyProperties(sc, rsc);
					rsc.setSerialContentId(sc.getId());
					contentList.add(rsc);
				}
			}
			// 添加图片列表
			detail.setSerialContentImages(contentList);
		}
		return detail;
	}

	/**
	 * 普通期浏览量+1
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public synchronized void updateNomalSerialSeeCount(int serialId) {
		serialMapper.updateSerialSeeCount(serialId);
	}

	/**
	 * 根据期资讯ID获取本期详情（达人或讲师发布的期）
	 *
	 * @author 卫耀华
	 */
	@Override
	public ResponseTalentSerialDetail getTalentSerialDetailByTalentSerialId(int serialId, long userId, long shareUserId) throws BizException {
		int roleId = 0;
		User user = userMapper.selectByPrimaryKey(userId);
		if (user != null) {
			roleId = user.getRoleId();
		}
		int shareRoleId = 0;
		User shareUser = userMapper.selectByPrimaryKey(shareUserId);
		if (shareUser != null) {
			shareRoleId = shareUser.getRoleId();
		}
		//获取达人期详情
		TalentSerial serial = talentSerialMapper.selectTalentSerialById(serialId);
		ResponseTalentSerialDetail detail = null;
		if (serial != null) {
			detail = new ResponseTalentSerialDetail();
			BeanUtils.copyProperties(serial, detail);
			detail.setCoverImgpath(serial.getImagePath());
			detail.setSerialId(serial.getId());
			detail.setTalentId(serial.getTalentId());
			// 查询期下面的C区商品
			List<Goods> goodss = talentSerialGoodsMapper.selectGoodsByTalentSerialId(serialId);
			List<GoodsSimpleVo> simpleVoList = new ArrayList<GoodsSimpleVo>();
			if (goodss != null && goodss.size() > 0) {
				for (Goods goods : goodss) {
					GoodsSimpleVo vo = goodsService.toSimpleGoodsVo(goods, shareRoleId, roleId);
					if (vo != null) {
						simpleVoList.add(vo);
					}
				}
				detail.setWxSmallImgpath(simpleVoList.get(0).getGoodNavigateImage());//设置微信小图
			}
			// 商品列表
			detail.setGoodsList(simpleVoList);
			// 期详情的图片列表
			List<TalentSerialContent> contents = talentSerialContentMapper.selectTalentSerialContentListBySerialId(serialId);
			List<ResponseTalentSerialContent> respContents = new ArrayList<ResponseTalentSerialContent>();
			if (contents != null && contents.size() > 0) {
				for (TalentSerialContent sc : contents) {
					ResponseTalentSerialContent rsc = new ResponseTalentSerialContent();
					BeanUtils.copyProperties(sc, rsc);
					rsc.setTalentSerialContentId(sc.getId());
					rsc.setSerialId(sc.getTalentSerialId());
					respContents.add(rsc);
				}
			}
			detail.setSerialContentImages(respContents);
			//设置信息简介 单人昵称 头像 这里可能会报错 uu为空的时候
			User uu = userMapper.selectByPrimaryKey(serial.getTalentId());
			if (uu == null) {
				detail.setPersonDescription("");
				detail.setTalentHeadPhoto("");
				detail.setTalentNickName("");
			}
			detail.setPersonDescription(uu.getSynopsis());
			detail.setTalentHeadPhoto(uu.getPicture());
			detail.setTalentNickName(uu.getNickName());
			//用户是否关注讲师
			detail.setIsEnjoy(userService.userIsEnjoyTalent(userId, serial.getTalentId()));
		}
		return detail;
	}

	/**
	 * 达人期详情点击后，期浏览量+1
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public synchronized void updateTalentSerialSeeCount(int serialId) {
		talentSerialMapper.updateTalentSerialSeeCount(serialId);
	}

	/**
	 * 达人主页要展示的期
	 *
	 * @author 卫耀华
	 * @param id
	 * @param startIndex
	 * @param pageSize
	 * @return
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public List<SimpleSerialVo> selectTalentSerialByPagination(Long talentId, int startIndex, Integer pageSize) {
		List<SimpleSerialVo> voList = new ArrayList<SimpleSerialVo>();
		List<Integer> serialIds = talentSerialEditAndShareMapper.selectTalentSerialIdListByTalentId(talentId);
		if (serialIds != null && serialIds.size() > 0) {
			List<TalentSerial> talentSerials = talentSerialMapper.selectTalentSerialListByIdAndPage(serialIds, startIndex, pageSize);
			voList = toSimpleSerialList(talentSerials);
		}
		return voList;
	}

	/**
	 * 达人期（只显示商品数量，不含列表）
	 *
	 * @author 卫耀华
	 * @param talentSerials
	 * @return
	 */
	private List<SimpleSerialVo> toSimpleSerialList(List<TalentSerial> talentSerials) {
		List<SimpleSerialVo> voList = new ArrayList<SimpleSerialVo>();
		if (talentSerials != null && talentSerials.size() > 0) {
			for (TalentSerial ts : talentSerials) {
				SimpleSerialVo vo = new SimpleSerialVo();
				BeanUtils.copyProperties(ts, vo);
				vo.setSerialId(ts.getId());// 达人期ID
				vo.setCoverImgpath(ts.getImagePath());
				List<Goods> goodss = talentSerialGoodsMapper.selectGoodsByTalentSerialId(ts.getId());
				int goodsNum = 0;
				if (goodss != null && goodss.size() > 0) {
					for (Goods goods : goodss) {
						if (goods != null) {
							goodsNum = goodsNum + 1;
						}
					}
				}
				vo.setGoodsNum(goodsNum);// 商品数量
				voList.add(vo);
			}
		}
		return voList;
	}

	/**
	 * 统计达人主页期资讯总个数
	 *
	 * @author 卫耀华
	 * @param talentId
	 * @return
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	@Override
	public int countTalentSerialNumByTalentId(Long talentId) {
		int num = 0;
		List<Integer> serialIds = talentSerialEditAndShareMapper.selectTalentSerialIdListByTalentId(talentId);
		if (serialIds != null && serialIds.size() > 0) {
			num = talentSerialMapper.selectTalentSerialNumById(serialIds);
		}
		return num;
	}

	/**
	 * 热门资讯(浏览数最多的资讯)
	 *
	 * @author 卫耀华
	 */
	@Override
	public List<SimpleSerialVo> selectHotSerials() {
		List<SimpleSerialVo> voList = new ArrayList<SimpleSerialVo>();
		List<Serial> serials = serialMapper.selectHotSerials();
		if (serials != null && serials.size() > 0) {
			for (Serial s : serials) {
				voList.add(nomalSerialNoGoods(s));
			}
		}
		return voList;
	}

	/**
	 * 达人进入我的资讯
	 *
	 * @author 卫耀华
	 * @param talentId
	 * @param startIndex
	 * @param pageSize
	 * @return
	 */
	@Override
	public List<ResponseSerial> myTalentSerialList(Long talentId, int startIndex, Integer pageSize) {
		int roleId = 0;
		User user = userMapper.selectByPrimaryKey(talentId);
		if (user != null) {
			roleId = user.getRoleId();
		}
		List<ResponseSerial> voList = new ArrayList<ResponseSerial>();
		List<Integer> serialIds = talentSerialEditAndShareMapper.selectTalentSerialIdListByTalentId(talentId);
		if (serialIds != null && serialIds.size() > 0) {
			List<TalentSerial> talentSerials = talentSerialMapper.selectTalentSerialListByIdAndPage(serialIds, startIndex, pageSize);
			voList = talentSerialNeedGoods(talentSerials, roleId);
		}
		return voList;
	}

	/**
	 * 达人进入我的资讯
	 *
	 * @author 卫耀华
	 * @param talentId
	 * @return
	 */
	@Override
	public int countMyTalentSerialList(Long talentId) {
		int num = 0;
		List<Integer> serialIds = talentSerialEditAndShareMapper.selectTalentSerialIdListByTalentId(talentId);
		if (serialIds != null && serialIds.size() > 0) {
			num = talentSerialMapper.selectTalentSerialNumById(serialIds);
		}
		return num;
	}

	@Override
	public ResponseSerialVo selectTalentSerial(int talentSerialId, long userId) {
		ResponseSerialVo responseSerialVo = new ResponseSerialVo();

		// 设置达人期内容
		List<TalentSerialContent> talentSerialContentList = talentSerialContentMapper.selectTalentSerialContentListBySerialId(talentSerialId);
		responseSerialVo.setTalentSerialContentList(talentSerialContentList);
		// 达人期商品id集合
		List<Long> goodIdList = talentSerialGoodsMapper.selectGoodsIdsByTalentSerialId(talentSerialId);
		List<GoodVo> goodVoList = new ArrayList<GoodVo>();
		User user = userMapper.selectUserEntityByIdNoPassword(userId);
		for (long goodId : goodIdList) {
			GoodVo goodVo = new GoodVo();
			GoodsNavigate goodsNavigate = goodsNavigateMapper.selectGoodsNavigateByGoodIdGetOne(goodId);
			goodVo.setGoodNavigateImage(goodsNavigate.getNavigateImage());
			Goods goods = goodsMapper.selectGoodsById(goodId);
			GoodsDetail GoodsDetail = goodsDetailMapper.selectGoodsDetailById(goodId, GoodsImgType.DETAIL.getType());
			// 设置商品信息
			goodVo.setGoodId(goods.getId());
			goodVo.setLabelName(goods.getName());
			goodVo.setImgWidth(GoodsDetail.getImageWidth());
			goodVo.setImgHeight(GoodsDetail.getImageHeight());
			goodVo.setSuggestedPrice(goods.getSuggestedPrice());
			goodVo.setLowestPrice(goodsService.getLowestPrice(goods, 0, user.getRoleId()));
			goodVoList.add(goodVo);
			responseSerialVo.setGoodVoList(goodVoList);
		}
		//根据期资讯ID获取达人讲师期详情(status=1)
		TalentSerial talentSerial = talentSerialMapper.selectTalentSerialById(talentSerialId);
		responseSerialVo.setResponseSerialVo(talentSerial);
		//达人期下的商品个数
		responseSerialVo.setGoodCount(talentSerialGoodsMapper.selectGoodsIdsByTalentSerialIdcount(talentSerialId));
		return responseSerialVo;
	}

}
